import {defineStore} from "pinia";
import {Post, Summary} from "@/types/data";
import request from "@/untils/request";
import {ElMessage} from "element-plus";

const postsStore = defineStore('posts', {
    state() {
        return {
            list: [] as Post[],
        }
    },
    actions: {
        async getPosts(page: number) {
            request.get('/postInfo/queryAll', {
                params: {
                    page,
                }
            }).then((res: any) => {
                if (res.data.code !== 0) {
                    ElMessage.error('获取失败');
                    return;
                }
                new Promise((resolve) => {
                    this.list = [];
                    resolve(true);
                }).then(() => {
                    for (let i of res.data.data)
                        this.list.push(i);
                });
            }).catch(() => ElMessage.error('网络错误'));
        },
        getSummary(passage: string, len: number) {
            return {
                dots: passage.length > len,
                sum: passage.substring(0, len - 1),
            } as Summary;
        }
    }
});

export default postsStore;
